import React, { useEffect, useState } from "react";
import styled from "styled-components";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFileAlt, faEdit, faTrashAlt, faTimes } from "@fortawesome/free-solid-svg-icons";
import PropTypes from "prop-types";
import useKeyHandler from '../hooks/useKeyHandler';
import useConenxtMenu from '../hooks/useConenxtMenu';
import { getParentNode } from '../utils/helper';

// ul 标签
const GroupUl = styled.ul.attrs({
  className: "list-group list-group-flush menu-box"
})`
  span {
    display: inline-block;
  }
  input {
    margin-right: 20px;
  }
  li {
    color: #fff;
    background: none;
  }
`;

FileList.propTypes = {
  files: PropTypes.array.isRequired,
  editFile: PropTypes.func.isRequired,
  saveFile: PropTypes.func.isRequired,
  deleteFile: PropTypes.func.isRequired,
}

export default function FileList({ files, editFile, saveFile, deleteFile }) {
  const [editItem, setEditItem] = useState("");
  const [value, setValue] = useState("");
  const enterPressed = useKeyHandler(13);
  const escPressed = useKeyHandler(27);
  // 右键菜单
  const contextMenuTmp = [
    {
      label: "重命名",
      click: () => {
        const retNode = getParentNode(currentEle.current, "menu-item");
        if (!retNode) return;
        setEditItem(retNode.dataset.id);
      }
    },
    {
      label: "删除",
      click: () => {
        const retNode = getParentNode(currentEle.current, "menu-item");
        if (!retNode) return;
        deleteFile(retNode.dataset.id);
      }
    },
  ];
  
  const currentEle = useConenxtMenu(contextMenuTmp, ".menu-box");

  // 关闭行为
  const closeEdit = () => {
    setEditItem("");
    setValue("");
  };

  // 新增文件时编辑其他， 存在bug
  // useEffect(() => {
  //   const newFile = files.find(file => file.isNew);
  //   if (newFile && editItem === newFile.id) deleteFile(newFile.id);
  // }, [editItem]);

  // 新建文件
  useEffect(() => {
    const newFile = files.find(file => file.isNew);
    if (newFile) {
      setEditItem(newFile.id);
      setValue("");
    }
  }, [files]);

  // 键盘监听
  useEffect(() => {
    if (enterPressed && editItem && value.trim() !== "") {
      const file = files.find(file => file.id === editItem);
      saveFile(editItem, value, file.isNew);
      closeEdit();
    }
    if (escPressed && editItem) {
      closeEdit();
    }
  });

  return (
    <GroupUl>
      {files.map(file => (
        <li className="list-group-item d-flex align-items-center menu-item" key={file.id} data-id={file.id} data-title={file.title}>
          {file.id === editItem || file.isNew ? (
            <>
              <input 
                value={value}
                className="col-8" 
                onChange={e => setValue(e.target.value)}
              />
              <span className="col-3">
                <FontAwesomeIcon onClick={closeEdit} icon={faTimes} />
              </span>
            </>
          ) : (
            <>
              <span className="col-1">
                <FontAwesomeIcon icon={faFileAlt} />
              </span>
              <span className="col-8" onClick={() => {editFile(file.id); closeEdit();}}>
                {file.title}
              </span>
              <span className="col-2">
                <FontAwesomeIcon onClick={() => setEditItem(file.id)} icon={faEdit} />
              </span>
              <span onClick={() => deleteFile(file.id)} className="col-2">
                <FontAwesomeIcon icon={faTrashAlt} />
              </span>
            </>
          )}
        </li>
      ))}
    </GroupUl>
  );
}
